<template>
  <openlayer-base-map class="complain_map" ref="refOpenlayerBaseMap" :currentPageType="'complain'" :isShowLend="true"
    @getOlMapInstance="getOlMapInstance" @getCurrentViewData="getCurrentViewData" :isAutoRenderData="true"
    :isControlOverviewInfo="true" @getAreaData="getComplainData" @reflashMap="reflashMap"
    @toggleOverviewInfo="toggleOverviewInfo" :key="Math.random()" :minRenderZoom="13">

    <el-button type="primary" @click="reflashMap" class="reflash_map">刷新地图</el-button>

    <!-- 右侧信息 - 投诉信息 -->
    <complain-common v-show="isShowComplainCommon" :circleLength="circleLength" @showDialog="showDialog"
      @setComplainByTime="setComplainByTime" @renderGeojsonByCounty="renderGeojsonByCounty" />

    <!-- 自定义圆形数据 -->
    <circle-info-dialog ref="refCircleInfoDialog" />

    <!-- 投诉列表 -->
    <complaint-info-dialog ref="refComplaintInfoDialog" @setAutoPopup="setComplaintAutoPopup" />

    <!-- 预警列表 -->
    <warning-info-dialog ref="refWarningInfoDialog" @setAutoPopup="setWarningAutoPopup" />
  </openlayer-base-map>
</template>

<script setup name="Complain">
// vue - core
import { ref, onUnmounted, nextTick } from "vue";
// 组件
import OpenlayerBaseMap from "@/components/OpenlayerBaseMap/index.vue";
import CircleInfoDialog from "./components/CircleInfoDialog.vue"; // 点击圆信息
import ComplainCommon from "./components/ComplainCommon.vue"; // 投诉信息
import ComplaintInfoDialog from "./components/ComplaintInfoDialog.vue"; // 投诉列表
import WarningInfoDialog from "./components/WarningInfoDialog.vue"; // 预警列表
import { getPopupInnerDom, getPopupAnalysisDom, getFeaturesPopupInnerDom } from "./components/popup/complainPopup.jsx"; // 气泡窗dom
// api相关 - 工具
import { apiCommon, getFormulateDate, moreArraysIsEmpty } from "@/utils/index.js";
import * as complainApi from "@/api/complain/complain";
import * as gisApi from "@/api/gis/gis";
// 工具
import mittBus from "@/utils/mittBus"; // mitt - 组件传参工具
import { complainDataStore } from '@/store/modules/complain.js'  // store
// geojson
import haishu from "./geojson/haishu.json";
import yinzhou from "./geojson/yinzhou.json";
import jiangbei from "./geojson/jiangbei.json";
import zhenhai from "./geojson/zhenhai.json";
import beilun from "./geojson/beilun.json";
import fenghua from "./geojson/fenghua.json";
import cixi from "./geojson/cixi.json";
import yuyao from "./geojson/yuyao.json";
import ninghai from "./geojson/ninghai.json";
import xiangshan from "./geojson/xiangshan.json";
// svg
import complainMarker1 from "./icon/complain_marker1.svg";
import complainMarker2 from "./icon/complain_marker2.svg";
import complainMarker3 from "./icon/complain_marker3.svg";
import arrow from "./icon/arrow.svg";
import alarmPoint from "./icon/analysisPoint/alarmPoint.svg";
import interferencePoint from "./icon/analysisPoint/interferencePoint.svg";
import loadPoint from "./icon/analysisPoint/loadPoint.svg";
import performancePoint from "./icon/analysisPoint/performancePoint.svg";

const refOpenlayerBaseMap = ref(null); // 地图核心元素

const { proxy } = getCurrentInstance();

const refCircleInfoDialog = ref(null);
const refComplaintInfoDialog = ref(null);
const refWarningInfoDialog = ref(null);

const complainStoreData = complainDataStore()

let isShowComplainCommon = ref(true)

let myOlMap = null;
let myMapCommonData = null;

let complainDataList = null

let currentZoom = ref(0);
let circleLength = ref(0);

/**
 * 接收其他组件派发的方法
 */
// 获取当前zoom
mittBus.on("getCurrentZoom", ({ zoom, minRenderZoom }) => {
  // console.log("当前缩放级别为：" + zoom, minRenderZoom);

  currentZoom.value = zoom;
});
/**
 * 气泡窗
 */
// 设置通用气泡窗html
mittBus.on("setCommonPopupInner", ({ popupObj, featureItem, callback }) => {
  // console.log("设置通用气泡窗html", popupObj, featureItem, featureItem.get('bussinessType'), featureItem.get('bussinessType'), 'analysisMarker');

  if (featureItem && featureItem.get('bussinessType') === 'analysisMarker') {
    callback(getPopupAnalysisDom(popupObj));
  } else {
    callback(getPopupInnerDom(popupObj));
  }

});
// 设置重叠要素气泡窗html
mittBus.on('setFeaturesPopupInner', ({ popupObj, callback, next }) => {
  // console.log(popupObj, callback)

  callback(getFeaturesPopupInnerDom(popupObj, currentDataList => {
    // console.log(currentDataList)

    currentDataList = currentDataList.filter(item => item)
    // console.log(currentDataList)

    next(currentDataList)
  }));
})
//  气泡窗点击更多 - 子组件使用
mittBus.on("popupDataGetMore", async ({ currentPopupObj, callback }) => {
  // console.log("气泡窗点击更多", currentPopupObj);

  if (!currentPopupObj.currentPopupData) {
    currentPopupObj.currentPopupData = currentPopupObj.popupData
  }

  // 或者走接口,根据cgi获取详情
  // console.log(currentPopupObj)
  const currentPopupAsyncObj = await apiCommon(complainApi.queryComplaintInfo, {
    complaintId: currentPopupObj.currentPopupData.complaintId,
  });
  currentPopupObj = currentPopupAsyncObj.data;
  // console.log(currentPopupAsyncObj);

  // 获取完数据后进行弹窗
  callback(currentPopupObj);
});
//  数据分析
mittBus.on("analysisPointData", async (currentData) => {
  console.log("数据分析", currentData.longitude, currentData.latitude);

  let startPixelPoint = refOpenlayerBaseMap.value.transformToPixelPoint(currentData.longitude, currentData.latitude)
  // console.log(currentPixelPoint)

  /* 分析状态[空 - 未匹配到分析结果.完成 - loadResult]
  未匹配到小区

  展示分析结果 */
  proxy.$modal.loading("正在请求中，请稍候...");

  let analysisPointRes = await apiCommon(complainApi.queryComplaintAnalysisResult, currentData.csId);
  // let analysisPointRes = await apiCommon(complainApi.queryComplaintAnalysisResult, '20240603103828X13147');
  proxy.$modal.closeLoading();

  analysisPointRes = analysisPointRes.data;
  // console.log(analysisPointRes);

  if (analysisPointRes) {
    const { alarmResult, interferenceResult, loadResult, performanceResult } = analysisPointRes
    const tempArr = [alarmResult, interferenceResult, loadResult, performanceResult]

    if (moreArraysIsEmpty(tempArr)) {
      proxy.$modal.msgWarning(`未匹配到小区`);
      return
    }

    refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "analysisMarker"); // 根据类型移除图层 - 分析标注
    refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "complainArrowLine"); // 根据类型移除图层 - 分析箭头
    // refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "complainTextPoint"); // 根据类型移除图层 - 分析文本

    // 显示图例
    mittBus.emit('showLend')

    console.log(currentData)

    proxy.$modal.loading("正在调整视图，请稍候...");
    myOlMap.getView().setZoom(16)
    setTimeout(() => {
      /* 
      queryComplaintList 返回结果新增字段
      analysisResult 分析状态
      alarmResult 故障分析 - #d81e06
      interferenceResult 高干扰分析 - #cfa4ff
      performanceResult 性能分析 - #409eff
      loadResult 高负荷分析 - #e2aa53
    */
      // console.log(alarmResult, interferenceResult, loadResult, performanceResult)
      setComplainAnalysisData(alarmResult, startPixelPoint, '故障分析', alarmPoint)
      setComplainAnalysisData(interferenceResult, startPixelPoint, '高干扰分析', interferencePoint)
      setComplainAnalysisData(loadResult, startPixelPoint, '性能分析', loadPoint)
      setComplainAnalysisData(performanceResult, startPixelPoint, '高负荷分析', performancePoint)

      refOpenlayerBaseMap.value.flyToCoordinate(myOlMap, [currentData.longitude, currentData.latitude]);
      proxy.$modal.closeLoading();

      getCurveData()
    }, 3000);
  }
});
// 设置圆形数据
mittBus.on("setCircleDialogData", (circleData) => {
  // console.log("setCircleDialogData", circleData);
  if (refCircleInfoDialog.value) {
    refCircleInfoDialog.value.show(circleData);
  }
});

/**
 * 工具方法
 */
// 分析数据批量处理要素
const setComplainAnalysisData = (resDataList, startPixelPoint, typeTxt, pointIcon) => {
  if (resDataList.length !== 0) {
    resDataList.forEach(item => {

      item.analysisType = typeTxt

      let analysisPointItem = {
        lonlat: [item.longitude, item.latitude],
        pointData: item,
      }

      let endPixelPoint = refOpenlayerBaseMap.value.transformToPixelPoint(item.longitude, item.latitude)

      let position = [startPixelPoint, endPixelPoint]
      refOpenlayerBaseMap.value.addArrowLine(myOlMap, position, arrow, 'complainArrowLine')

      // 创建文本要素以显示距离
      // refOpenlayerBaseMap.value.addTextPoint(myOlMap, typeTxt, [item.longitude, item.latitude], 'complainTextPoint')

      refOpenlayerBaseMap.value.addPoint(
        myOlMap,
        analysisPointItem,
        pointIcon,
        { bussinessType: 'analysisMarker', 'noPopup': true }, 999
      );
    })
  }
}

const getContyGeoJson = (val) => {
  let geojsonData = null
  switch (val) {
    case '海曙':
      geojsonData = haishu
      break
    case '鄞州':
      geojsonData = yinzhou
      break
    case '江北':
      geojsonData = jiangbei
      break
    case '镇海':
      geojsonData = zhenhai
      break
    case '北仑':
      geojsonData = beilun
      break
    case '奉化':
      geojsonData = fenghua
      break
    case '慈溪':
      geojsonData = cixi
      break
    case '余姚':
      geojsonData = yuyao
      break
    case '宁海':
      geojsonData = ninghai
      break
    case '象山':
      geojsonData = xiangshan
      break
    default:
      break
  }

  return geojsonData
}

// 渲染区县geojson
const renderGeojsonByCounty = (val) => {
  // console.log('区县', val)

  let geojsonData = getContyGeoJson(val)
  // console.log(geojsonData.features[0].properties.name)

  myOlMap.getView().setZoom(myOlMap.getView().getMinZoom()); // 修改至最小zoom

  refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "countyGeoJson"); // 根据类型移除图层

  // 获取geojson中心点
  let centerCoordinates = geojsonData.features[0].properties.center
  // console.log(centerCoordinates)

  // 调用函数飞到指定的坐标
  refOpenlayerBaseMap.value.flyToCoordinate(myOlMap, centerCoordinates);

  // 渲染geojson
  refOpenlayerBaseMap.value.renderGeojsonByCounty(myOlMap, geojsonData, feature => {
    // console.log(feature.get("type"), feature)

    let polygonCenter = feature.get('centroid')

    refOpenlayerBaseMap.value.addTextPoint(myOlMap, feature.get('name'), polygonCenter, { businessType: 'geojsonLabel' }, currentFeature => {
      // console.log(currentFeature)

      return currentFeature.get('businessType') === 'geojsonLabel'
    });
  }, refOpenlayerBaseMap.value.setFeaturesStyle(
    "rgba(255, 255, 255, 0.8)",
    "#e4e7ed"
  ))
}

const getCurveData = () => {
  // myOlMap.getView().setZoom(18)

  let getCurrentSectorData = async () => {
    console.log("请求扇区")
    proxy.$modal.loading("正在请求扇区数据，请稍候...");

    let params = {
      ...getCurrentPositionParams(myOlMap),
      networkType: "all",
    };

    let gisData = await apiCommon(gisApi.queryGisList, params);
    let { cell4gList, cell5gList } = gisData.data;
    /* cell4gList = cell4gList.map(item => {
      item.networkType = "4g";
      return item
    })
    cell5gList = cell5gList.map(item => {
      item.networkType = "5g";
      return item
    }) */
    renderFeatureByData0(myOlMap, cell4gList);
    renderFeatureByData0(myOlMap, cell5gList);

    // let allCurrentData = [...cell4gList, ...cell5gList]
    // console.log(allCurrentData)

    // console.log(cell4gList)

    /* if (cell4gList) {
      cell4gList.forEach((item) => {
        item.networkType = "4g";
      });
    }
  
    if (cell5gList) {
      cell5gList.forEach((item) => {
        item.networkType = "5g";
      });
    }
  
    let allCurrentData = [...cell4gList, ...cell5gList] */

    proxy.$modal.closeLoading();

    console.log(params)
  }

  setTimeout(() => {
    getCurrentSectorData(myOlMap)
  }, 1000);
}

// 根据数据渲染Feature
const renderFeatureByData0 = (olMap, dataList) => {
  refOpenlayerBaseMap.value.renderFeatureByData(
    olMap,
    dataList,
    (olMap, item) => {
      if (item.coverType === "室外") {
        // console.log(item.workFrequency)

        let outPoint = [];
        outPoint.push({
          lonlat: [item.longitude, item.latitude],
          // 需要有antDirectionAngle字段
          curveData: item,
        });
        // 批量添加扇形
        refOpenlayerBaseMap.value.addCurve(olMap, outPoint, (item) => {
          return renderCurveByField(item.curveData);
        });
      }
    }
  );
};

// 根据字段渲染扇形
const renderCurveByField = (curveData, optity = 0.4) => {
  return renderCurveByFrequency(curveData, (optity = 0.4));
};

// 根据频率渲染扇形
const renderCurveByFrequency = (curveData, optity = 0.4) => {
  // console.log("根据频率渲染扇形");

  let myCurveStyle = null; // 扇区样式
  let myStrokeColor = "rgba(255, 205, 67, 0.3)";
  let myCurveRadius = 0; // 扇区半径

  /**
   * 根据频率获取数据
   *
   * A频段  100  填充: rgba(200, 22, 100, 0.4)   线:
   * D频段  110  填充: rgba(55, 33, 188, 0.4)   线:
   * E频段  120  填充: rgba(88, 99, 200, 0.4)   线:
   * F频段  130  填充: rgba(255, 255, 0, 0.4)   线:
   * FDD  140   填充:  rgba(255, 76, 127, 0.4)  线:
   * 其他  150  填充:  rgba(32, 222, 230, 0.4)   线 : rgba(255, 205, 67, 0.3)
   */
  switch (curveData.workFrequency) {
    case "A频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(200, 22, 100, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 100;
      break;
    case "D频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(55, 33, 188, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 110;
      break;
    case "E频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(88, 99, 200, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 120;
      break;
    case "F频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 255, 0, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 130;
      break;
    case "FDD":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 76, 127, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 140;
      break;
    default:
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(32, 222, 230, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 150;
      break;
  }

  return { myCurveStyle, myCurveRadius };
};

// 显示隐藏概览
const toggleOverviewInfo = (val) => {
  // console.log('显示隐藏概览', val)

  isShowComplainCommon.value = val
}
// 刷新地图
const reflashMap = () => {
  refOpenlayerBaseMap.value.removeAllLayer(myOlMap)

  getComplainData(myOlMap)
  getCurrentViewData(myOlMap)
}
// 获取可视区域坐标参数
const getCurrentPositionParams = (olMap) => {
  let viewPosition = refOpenlayerBaseMap.value.getCurrentViewPosition(olMap);
  // console.log("获取可视区域的左上角和右下角坐标", viewPosition)

  return {
    minLatitude: viewPosition.bottomRight[1],
    maxLatitude: viewPosition.topLeft[1],
    minLongitude: viewPosition.topLeft[0],
    maxLongitude: viewPosition.bottomRight[0],
  };
};

/**
 * 业务方法
 */
// 获取地图实例 - 地图加载完初始化做的一些操作[业务相关]
const getOlMapInstance = (olMap, mapCommonData) => {
  // console.log("获取地图实例 - 地图加载完初始化做的一些操作[业务相关]", olMap);

  olMap.getView().setZoom(11)

  myOlMap = olMap; // 赋值全局变量,为后续业务操作做准备

  myMapCommonData = mapCommonData;

  // 2024-07-09
  /* let startPixelPoint = refOpenlayerBaseMap.value.transformToPixelPoint(121.616247, 29.876098)
  let endPixelPoint = refOpenlayerBaseMap.value.transformToPixelPoint(121.628471, 29.883743)
  let position = [startPixelPoint, endPixelPoint]
  console.log(position)

  refOpenlayerBaseMap.value.addArrowLine(olMap, position, arrow, 'complainArrowLine') */
};
// 获取可视区域数据 (主入口)
const getCurrentViewData = async (olMap) => {
  let params = {
    ...getCurrentPositionParams(olMap),
    dateString: complainStoreData.complainTime
  };

  proxy.$modal.loading("正在请求中，请稍候...");

  complainDataList = await apiCommon(complainApi.queryComplaintList, params);
  complainDataList = complainDataList.data;

  renderFeatureByData(olMap, complainDataList);

  proxy.$modal.closeLoading();
};

// 根据数据渲染Feature
const renderFeatureByData = (olMap, dataList) => {
  refOpenlayerBaseMap.value.renderFeatureByData(olMap, dataList, (olMap, dataList) => {
    // console.log(olMap, dataList)

    // let tempArr = []
    let temp4GArr = []
    let temp4GVOLTEArr = []
    let temp5GArr = []
    dataList.forEach(item => {
      item.dispatchTime = getFormulateDate(item.dispatchTime)
      item.isNeedAnalysis = true  // 判断是否需要进行数据分析
      if (item.category === '4G上网') {
        temp4GArr.push({
          lonlat: [item.longitude, item.latitude],
          pointData: item,
        })
      }
      if (item.category === '4GVOLTE') {
        temp4GVOLTEArr.push({
          lonlat: [item.longitude, item.latitude],
          pointData: item,
        })
      }
      if (item.category === '5G上网') {
        temp5GArr.push({
          lonlat: [item.longitude, item.latitude],
          pointData: item,
        })
      }
    })

    refOpenlayerBaseMap.value.addPoint(olMap, temp4GArr, complainMarker1);
    refOpenlayerBaseMap.value.addPoint(olMap, temp4GVOLTEArr, complainMarker2);
    refOpenlayerBaseMap.value.addPoint(olMap, temp5GArr, complainMarker3);
  }, false)


};

// 设置圆数据(投诉)
const getComplainData = async (olMap) => {
  // console.log(olMap);
  let params = {
    date: complainStoreData.complainTime
  }

  let circleList = await apiCommon(complainApi.queryComplaintCluster, params);
  circleList = circleList.data
  circleLength.value = circleList.length

  refOpenlayerBaseMap.value.renderFeatureByData(
    olMap,
    circleList,
    (olMap, item) => {

      item.lonlat = [item.longitude, item.latitude]
      // item.radius = 450

      // 添加圆
      refOpenlayerBaseMap.value.addCircle(olMap, item, { bussinessType: 'complain' }, true, false);
      /* refOpenlayerBaseMap.value.addCircle(olMap, item, { bussinessType: 'complain' }, false, false);
      refOpenlayerBaseMap.value.addCircle2(olMap, item, { bussinessType: 'complain' }); */
    }
  );
};

// 显示弹窗
const showDialog = (val, obj) => {
  // console.log('显示弹窗', val, obj)

  switch (val) {
    case 'gyyj':
      // console.log('投诉')
      refComplaintInfoDialog.value.show(obj);
      break;
    case 'yjqy':
      // console.log('预警')
      refWarningInfoDialog.value.show();
      break;
  }
}

// 修改投诉时间
const setComplainByTime = () => {
  // console.log("修改投诉时间", )

  reflashMap()
}

// 关闭弹窗
const closeDialog = val => {
  // console.log('关闭弹窗', val)

  switch (val) {
    case 'complain':
      dialogComplain.value = false
      break;
    case 'circle':
      dialogCircle.value = false
      break;
  }
}

const setComplaintAutoPopup = (val) => {
  refOpenlayerBaseMap.value.setMapByAutoPopupData(
    myOlMap,
    val,
    null,
    (olMap, dataList) => {
      reflashMap()
    }
  );
}


const setWarningAutoPopup = (val) => {
  // console.log("跳转气泡窗")

  // 调用函数飞到指定的坐标
  refOpenlayerBaseMap.value.flyToCoordinate(myOlMap, [val.longitude, val.latitude]);
}

/**
 * 生命周期
 */
onUnmounted(() => {
  // console.log('onUnmounted')

  mittBus.all.delete('popupDataGetMore')
})
</script>

<style lang="scss" scoped>
.complain_map {
  :deep .ol_map {
    .ol-popup {
      .popup_wrap {
        height: 220px;

        .common_popup_item {
          min-width: 472px;
        }
      }
    }
  }

  :deep .lend_wrap {
    /* position: relative;
    bottom: 216px;
    left: 66px;
    width: 168px; */

    .toggle {}
  }
}
</style>
